package com.polaris.live.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.mvvm.viewmodel.SingleLiveEvent
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.resp.UserResp
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.manager.AssetsConfigManager
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.resp.back_resp.IpCountryResp
import com.polaris.live.resp.back_resp.RandomNameResp
import com.polaris.live.resp.go_resp.InfoModifyBean
import kotlinx.coroutines.launch

/**
 * InfoUserViewModel
 *
 * @author Created by 半仙 on 2023/9/23/023 14:37
 */
class InfoUserViewModel : BaseViewModel() {

    //获取个人用户信息
    val mUserLiveData = MutableLiveData<UserResp>()
    fun getUser() {
        request({ userService.getUserData() }, {
            UserManager.setUser(it)
            mUserLiveData.value = it
        })
    }

    //完善资料
    val mInfoUpLiveData = MutableLiveData<ResultState<Any>>()
    fun infoUpData(infoModifyBean: InfoModifyBean) {
        request({ userService.infoModify(infoModifyBean) }, mInfoUpLiveData)
    }

    val mInfoUpNameLiveData = SingleLiveEvent<Unit>()
    fun infoUpNameData(nikeName: String) {
        requestLoading({ userService.infoModify(InfoModifyBean(nickname = nikeName)) }, {
            mInfoUpNameLiveData.value = Unit
        }, {
            if (it.errCode == CommonConst.ErrorCode.INFO_MODIFY) {
                ToastGravity.showGravity(it.errorMsg)
                getRandom(nikeName)
            } else {
                ToastGravity.showGravity(it.errorMsg)
            }
        })
    }

    //获取三个随机昵称
    val mRandomNameLiveData = SingleLiveEvent<List<RandomNameResp>>()
    fun getRandom(nikeName: String) {
        request({ userService.getRandomName(nikeName) }, {
            mRandomNameLiveData.value = it
        }, {
            ToastGravity.showGravity(it.errorMsg)
        })
    }

    //获取当前ip
    val mIpLiveData = SingleLiveEvent<ResultState<IpCountryResp>>()
    fun getIp() {
        val uniqueId = AppModule.requireUniqueDeviceId()

        request({ userService.getIp(uniqueId) }, mIpLiveData)
    }

    //获取所有的区号
    val mAllAreaCodeLiveData = SingleLiveEvent<List<AreaCodeResp>>()
    fun getAllAreaCode() {
        viewModelScope.launch {
            mAllAreaCodeLiveData.value = AssetsConfigManager.getCountryAreaCodes()
        }
    }
}